package logic

import (
	"anban/service"
	"anban/utils"
	"anban/utils/wechat"
	"fmt"
	"github.com/astaxie/beego"
	"net/url"
	"time"
)

// 发布作业
func AddHomework(input url.Values) *utils.Error {
	if len(input["class_id"][0]) <= 0 {
		return utils.NewError(0, "请选择班级")
	}
	if len(input["user_id"][0]) <= 0 {
		return utils.NewError(0, "请选择发布人")
	}
	if len(input["course_id"][0]) <= 0 {
		return utils.NewError(0, "请选择科目")
	}
	if len(input["content"][0]) <= 0 {
		return utils.NewError(0, "请输入作业内容")
	}

	homeworkId, err := service.AddHomework(input)
	if err != nil {
		return utils.NewError(0, "作业发布失败")
	}

	p := map[string]interface{}{}
	p["id"] = input["class_id"][0]
	p["relation"] = true
	class := service.GetClassInfo(p)

	if class.School.IsUseHomework == 1 {
		addInput := url.Values{
			"class_id": {input["class_id"][0]},
			"type": {"3"},
		}
		service.AddNewNotices(addInput)

		addInput = url.Values{
			"homework_id": {fmt.Sprintf("%d", homeworkId)},
			"class_id": {input["class_id"][0]},
		}
		service.AddHomeworkNotices(addInput)

		go SendHomeworkWechatNotice(input)
	}

	return nil
}

// 发送微信作业通知
func SendHomeworkWechatNotice(input url.Values) {
	domain := beego.AppConfig.String("domain")
	path := beego.URLFor("parent.HomeworkNoticeController.ShowList")
	wechatUrl := fmt.Sprintf("%s%s", domain, path)

	p := map[string]interface{}{}
	p["classId"] = input["class_id"][0]
	p["status"] = 1
	_, classStudentList := service.GetStudentList(p)

	for _, classStudent := range classStudentList {
		if len(classStudent.FamilySn) > 1 {
			p = map[string]interface{}{}
			p["status"] = 1
			p["familySn"] = classStudent.FamilySn
			_, parentList := service.GetUserList(p)
			for _, parent := range parentList {
				if parent.SubscribeStatus == 1 {
					wechat.SendHomeworkNotice(parent.OpenId, "您有新的作业通知", "", wechatUrl, classStudent.RealName, time.Now().Format("2006-01-02 15:04:05"), "无", "点击查看孩子作业")
				}
			}
		}
	}
	return
}
